'''
单链表反转2：
定位反转区间，反转后，将后面剩余的数据补上。
'''

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverseBetween(head: ListNode, left: int, right: int) -> ListNode:
    if not head or left == right:
        return head
    if head:
        print("list:", head.val)

    dummy = ListNode(0)
    dummy.next = head
    pre = dummy

    print("skip node:", left - 1)

    # 找到 left 的前一个节点
    for _ in range(left - 1):
        pre = pre.next

    print("reverse node:", right - left + 1)

    # 反转从 left 到 right 的部分
    curr = pre.next
    prev = None
    for _ in range(right - left + 1):
        next_node = curr.next
        curr.next = prev
        prev = curr
        curr = next_node
    if curr:
        print("curr:", curr.val)
    if prev:
        print("prev:", prev.val)
    if pre:
        print("pre:", pre.val)

    # 连接反转部分
    if pre.next.next:
        print("old next.next:", pre.next.next)
    else:
        print("old next.next:None")

    print("old next:", pre.next.val)

    pre.next.next = curr
    pre.next = prev

    return dummy.next

# 辅助函数：创建链表
def createList(values):
    if not values:
        return None
    head = ListNode(values[0])
    current = head
    for value in values[1:]:
        current.next = ListNode(value)
        current = current.next
    return head

# 辅助函数：打印链表
def printList(node: ListNode):
    while node:
        print(node.val, end=" -> ")
        node = node.next
    print("None")

# 测试用例
def test_reverseBetween():
    # 测试用例 1
    head1 = createList([1, 2, 3, 4, 5])
    left1 = 2
    right1 = 4
    result1 = reverseBetween(head1, left1, right1)
    print("Test case 1:")
    printList(result1)  # 预期输出: 1 -> 4 -> 3 -> 2 -> 5 -> None

    # 测试用例 2
    head2 = createList([5])
    left2 = 1
    right2 = 1
    result2 = reverseBetween(head2, left2, right2)
    print("Test case 2:")
    printList(result2)  # 预期输出: 5 -> None

    # 测试用例 3
    head3 = createList([1, 2, 3, 4, 5])
    left3 = 1
    right3 = 5
    result3 = reverseBetween(head3, left3, right3)
    print("Test case 3:")
    printList(result3)  # 预期输出: 5 -> 4 -> 3 -> 2 -> 1 -> None

    # 测试用例 4
    head4 = createList([1, 2, 3, 4, 5])
    left4 = 3
    right4 = 3
    result4 = reverseBetween(head4, left4, right4)
    print("Test case 4:")
    printList(result4)  # 预期输出: 1 -> 2 -> 3 -> 4 -> 5 -> None

    # 测试用例 5
    head5 = createList([1, 2, 3, 4, 5, 6, 7])
    left5 = 2
    right5 = 6
    result5 = reverseBetween(head5, left5, right5)
    print("Test case 5:")
    printList(result5)  # 预期输出: 1 -> 6 -> 5 -> 4 -> 3 -> 2 -> 7 -> None

# 运行测试用例
test_reverseBetween()
